import { ref } from 'vue';
import { useEventListener } from './useEventListener';

export function useMouse(options = {}) {
  const {
    // 基于页面、客户端或相对于先前位置的鼠标位置
    // 通过type参数取不同的属性
    type = 'page', // 'page' | 'client' | 'movement'
    // 监听 `touchmove` 事件
    touch = true,
    // 触发 "touchend" 事件时重置为初始值
    resetOnTouchEnds = false,
    // 初始值
    initialValue = { x: 0, y: 0 },
    // 自定义Handler触发时机
    eventFilter
  } = options;
  const x = ref(initialValue.x);
  const y = ref(initialValue.y);
  const sourceType = ref(null);
  const mouseHandler = (event) => {
    if (type === 'page') {
      x.value = event.pageX;
      y.value = event.pageY;
    } else if (type === 'client') {
      x.value = event.clientX;
      y.value = event.clientY;
    } else if (type === 'movement') {
      x.value = event.movementX;
      y.value = event.movementY;
    }
    sourceType.value = 'mouse';
  };
  const reset = () => {
    x.value = initialValue.x;
    y.value = initialValue.y;
  };
  const touchHandler = (event) => {
    // 触点的个数
    if (event.touches.length > 0) {
      const touch2 = event.touches[0];
      if (type === 'page') {
        x.value = touch2.pageX;
        y.value = touch2.pageY;
      } else if (type === 'client') {
        x.value = touch2.clientX;
        y.value = touch2.clientY;
      }
      sourceType.value = 'touch';
    }
  };
  const mouseHandlerWrapper = (event) => (!eventFilter ? mouseHandler(event) : eventFilter(() => mouseHandler(event), {}));
  const touchHandlerWrapper = (event) => (!eventFilter ? touchHandler(event) : eventFilter(() => touchHandler(event), {}));

  if (window) {
    // 监听鼠标移动事件
    useEventListener(window, 'mousemove', mouseHandlerWrapper, { passive: true });
    // 可拖动的元素被拖进一个有效的放置目标时（每几百毫秒）触发
    // 拖拽时不会触发 mousemove 事件
    useEventListener(window, 'dragover', mouseHandlerWrapper, { passive: true });
    // 兼容移动端 touch 事件
    if (touch && type !== 'movement') {
      useEventListener(window, 'touchstart', touchHandlerWrapper, { passive: true });
      useEventListener(window, 'touchmove', touchHandlerWrapper, { passive: true });
      if (resetOnTouchEnds) useEventListener(window, 'touchend', reset, { passive: true });
    }
  }
  return {
    x,
    y,
    sourceType
  };
}
